/**
 * 基础IPC服务
 * 提供统一的IPC通信接口和错误处理
 */
import {
  StandardResponse,
  ResponseCode,
  IPCError,
  ServiceResult as IServiceResult
} from '../types'

// 通过预加载脚本访问 ipcRenderer
const ipcRenderer = (window as any).electron?.ipcRenderer

/**
 * 安全调用IPC方法
 */
async function invokeSafe<T = any>(channel: string, ...args: any[]): Promise<{
  success: boolean
  data?: T
  error?: { message: string; code: number; data?: any }
}> {
  try {
    const response: StandardResponse<T> = await ipcRenderer.invoke(channel, ...args)

    if (response.code === ResponseCode.SUCCESS || response.code === ResponseCode.CREATED) {
      return {
        success: true,
        data: response.data
      }
    } else {
      return {
        success: false,
        error: {
          message: response.message,
          code: response.code,
          data: response.data
        }
      }
    }
  } catch (error) {
    return {
      success: false,
      error: {
        message: error instanceof Error ? error.message : '未知错误',
        code: ResponseCode.INTERNAL_ERROR,
        data: error
      }
    }
  }
}

/**
 * 调用IPC方法（抛出异常）
 */
async function invokeStandard<T = any>(channel: string, ...args: any[]): Promise<T> {
  const response: StandardResponse<T> = await ipcRenderer.invoke(channel, ...args)

  if (response.code === ResponseCode.SUCCESS || response.code === ResponseCode.CREATED) {
    return response.data as T
  } else {
    throw new IPCError(response.message, response.code, response.data)
  }
}

/**
 * 基础IPC服务类
 */
export class BaseIPCService {
  /**
   * 安全调用IPC方法
   * @param channel IPC通道
   * @param args 参数
   * @returns 结果对象
   */
  protected async invokeSafe<T = any>(channel: string, ...args: any[]): Promise<{
    success: boolean
    data?: T
    error?: { message: string; code: number; data?: any }
  }> {
    return await invokeSafe<T>(channel, ...args)
  }

  /**
   * 调用IPC方法（抛出异常）
   * @param channel IPC通道
   * @param args 参数
   * @returns 数据
   * @throws IPCError
   */
  protected async invoke<T = any>(channel: string, ...args: any[]): Promise<T> {
    return await invokeStandard<T>(channel, ...args)
  }

  /**
   * 处理IPC错误
   * @param error 错误对象
   * @param defaultMessage 默认错误消息
   * @returns 格式化的错误信息
   */
  protected handleError(error: any, defaultMessage: string = '操作失败'): {
    message: string
    code: number
    data?: any
  } {
    if (error instanceof IPCError) {
      return {
        message: error.message,
        code: error.code,
        data: error.data
      }
    }

    if (error && typeof error === 'object' && error.message) {
      return {
        message: error.message,
        code: ResponseCode.INTERNAL_ERROR,
        data: error
      }
    }

    return {
      message: defaultMessage,
      code: ResponseCode.INTERNAL_ERROR,
      data: error
    }
  }

  /**
   * 验证必需参数
   * @param params 参数对象
   * @param requiredFields 必需字段列表
   * @throws IPCError
   */
  protected validateRequired(params: any, requiredFields: string[]): void {
    for (const field of requiredFields) {
      if (params[field] === undefined || params[field] === null || params[field] === '') {
        throw new IPCError(`参数 ${field} 不能为空`, ResponseCode.VALIDATION_ERROR, { field })
      }
    }
  }

  /**
   * 验证字符串长度
   * @param value 字符串值
   * @param fieldName 字段名
   * @param maxLength 最大长度
   * @param minLength 最小长度
   * @throws IPCError
   */
  protected validateStringLength(
    value: string, 
    fieldName: string, 
    maxLength: number, 
    minLength: number = 0
  ): void {
    if (value.length < minLength) {
      throw new IPCError(
        `${fieldName}长度不能少于${minLength}个字符`, 
        ResponseCode.VALIDATION_ERROR, 
        { field: fieldName, minLength, actualLength: value.length }
      )
    }
    
    if (value.length > maxLength) {
      throw new IPCError(
        `${fieldName}长度不能超过${maxLength}个字符`, 
        ResponseCode.VALIDATION_ERROR, 
        { field: fieldName, maxLength, actualLength: value.length }
      )
    }
  }

  /**
   * 记录操作日志
   * @param operation 操作名称
   * @param params 参数
   * @param result 结果
   */
  protected log(operation: string, params?: any, result?: any): void {
    console.log(`[${this.constructor.name}] ${operation}`, {
      params,
      result,
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 记录错误日志
   * @param operation 操作名称
   * @param error 错误
   * @param params 参数
   */
  protected logError(operation: string, error: any, params?: any): void {
    console.error(`[${this.constructor.name}] ${operation} 失败`, {
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
      params,
      timestamp: new Date().toISOString()
    })
  }
}

/**
 * 服务结果类型
 */
export interface ServiceResult<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: {
    message: string
    code: number
    data?: any
  }
}

/**
 * 创建成功结果
 */
export function createSuccessResult<T>(data: T, message?: string): ServiceResult<T> {
  return {
    success: true,
    data,
    message
  }
}

/**
 * 创建错误结果
 */
export function createErrorResult(error: any, defaultMessage: string = '操作失败'): ServiceResult {
  const baseService = new BaseIPCService()
  return {
    success: false,
    error: baseService['handleError'](error, defaultMessage)
  }
}
